﻿using HospitalErpWinUI.GlobalVar;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
//using System.Web.Script.Serialization;
using System.Xml;

namespace Dao
{
    public class DaoHelper
    {
        string url;
        public DaoHelper()
        { 
            // 这里需要改成读配置文件
           // url = @"http://localhost:1278/Services";
            url = ConfigurationManager.AppSettings["ServicesAdress"];
        }

        #region 优化数据访问
        public DataTable ReadDictForSql(string service, string[] paramter)
        {

            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = service;

            if (paramter != null)
            {
                for (int i = 0; i < paramter.Length; i++)
                {
                    paramters.Add("paramter" + i, paramter[i].ToString());
                }
            }
            serviceParamter.Paramters = paramters;

            DataTable dt = this.ReadDictForSql(serviceParamter);
            return dt;
        }
        public List<CodeValue> ReadDictForData(string service, string[] paramter)
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = service;
            if (paramter != null)
            {
                 for (int i = 0; i < paramter.Length; i++)
                {
                    paramters.Add("paramter" + i, paramter[i].ToString());
                }
            }
           
            serviceParamter.Paramters = paramters;

            List<CodeValue> objs = this.ReadDictForData(serviceParamter);
            return objs;
        }
        public string ReadSqlForJson(string service, string[] paramter)
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = service;

            if (paramter != null)
            {
                for (int i = 0; i < paramter.Length; i++)
                {
                    paramters.Add("paramter" + i, paramter[i].ToString());
                }
            }
            serviceParamter.Paramters = paramters;

            string str = this.ReadSqlForJson(serviceParamter);
            return str;
        }
        public DataTable ReadSqlForDataTable(string service, string[] paramter)
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = service;

            if (paramter != null)
            {
                for (int i = 0; i < paramter.Length; i++)
                {
                    paramters.Add("paramter" + i, paramter[i].ToString());
                }
            }
            serviceParamter.Paramters = paramters;

            DataTable dt = this.ReadSqlForDataTable(serviceParamter);
            return dt;
        }
        public bool WirteSql(string service, string[] paramter)
        {
            ServiceParamter serviceParamter = new ServiceParamter();
            Dictionary<string, string> paramters = new Dictionary<string, string>();
            serviceParamter.ServiceId = service;

            if (paramter != null)
            {
                for (int i = 0; i < paramter.Length; i++)
                {
                    paramters.Add("paramter" + i, paramter[i].ToString());
                }
            }
            serviceParamter.Paramters = paramters;

            bool result = this.WirteSql(serviceParamter);
            return result;
        }
        #endregion

        #region 数据访问
        public DataTable ReadDictForSql(ServiceParamter serviceParamter)
        {
            DataTable dt = new DataTable();
            string data = string.Empty;
            string sqlId = serviceParamter.ServiceId;
            string ticString = JsonConvert.SerializeObject(serviceParamter);
            byte[] inArray = System.Text.Encoding.UTF8.GetBytes(ticString);
            string str = Convert.ToBase64String(inArray);
            str = str.Replace("+", "%2B").Replace("+", "%2B"); ;

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("serviceParamter", str);

            string realUrl = url + @"/GetServices/ReadDictSql";
            string result = HttpHelper.CreateHttpGetResponse(realUrl, dict, G_User.user.Ticket, sqlId);

            // JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            // string data = jo["Data"].ToString();

            ApiResultModel mode = Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(ApiResultModel)) as ApiResultModel;

            if (mode.IsSuccess)
            {
                data = mode.Data.ToString();
            }
            else
            {
                throw new Exception("服务器执行操作失败，错误详情请查看日志");
            }
            // JsonHelper helper = new JsonHelper();
            // dt = JsonHelper.ToDataTable(data);
            dt = Newtonsoft.Json.JsonConvert.DeserializeObject(data, typeof(DataTable)) as DataTable;

            return dt;
        }

        public List<CodeValue> ReadDictForData(ServiceParamter serviceParamter)
        {
            string data = string.Empty;
            string sqlId = serviceParamter.ServiceId;
            string ticString = JsonConvert.SerializeObject(serviceParamter);
            byte[] inArray = System.Text.Encoding.UTF8.GetBytes(ticString);
            string str = Convert.ToBase64String(inArray);
            str = str.Replace("+", "%2B");

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("serviceParamter", str);

            string realUrl = url + @"/GetServices/ReadDictData";
            string result = HttpHelper.CreateHttpGetResponse(realUrl, dict, G_User.user.Ticket, sqlId);
            //JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            //string data = jo["Data"].ToString();
            ApiResultModel mode = Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(ApiResultModel)) as ApiResultModel;

            if (mode.IsSuccess)
            {
                data = mode.Data.ToString();
            }
            else
            {
                throw new Exception("服务器执行操作失败，错误详情请查看日志");
            }
            data = data.Trim();
            if (string.IsNullOrEmpty(data))
            {
                return null;
            }
            data = Regex.Replace(data, @">\s+<", "><");
            //  data = data.Substring(data.IndexOf(@"<?xml version="), data.Length);
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(data);

            List<CodeValue> dicts = new List<CodeValue>();

            foreach (XmlNode node in xmldoc.DocumentElement.ChildNodes)
            {
                CodeValue codeValue = new CodeValue();

                codeValue.Code = node.Attributes["code"] == null ? "" : node.Attributes["code"].Value;
                codeValue.Value = node.Attributes["value"] == null ? "" : node.Attributes["value"].Value;
                dicts.Add(codeValue);
            }
            return dicts;
        }

        public string ReadSqlForJson(ServiceParamter serviceParamter)
        {
            string data = string.Empty;
            string sqlId = serviceParamter.ServiceId;
            string ticString = JsonConvert.SerializeObject(serviceParamter);
            byte[] inArray = System.Text.Encoding.UTF8.GetBytes(ticString);
            string str = Convert.ToBase64String(inArray);
            str = str.Replace("+", "%2B");

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("serviceParamter", str);

            string realUrl = url + @"/GetServices/ReadSql";
            try
            {
                string result = HttpHelper.CreateHttpGetResponse(realUrl, dict, G_User.user.Ticket, sqlId);

                ApiResultModel mode = Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(ApiResultModel)) as ApiResultModel;

                if (mode.IsSuccess)
                {
                    data = mode.Data.ToString();
                }
                else
                {
                    throw new Exception("服务器执行操作失败，错误详情请查看日志");
                }
                JsonHelper helper = new JsonHelper();
            }
            catch (Exception e)
            {
                throw ExceptionHandle(e);
            }


            return data;
        }

        public DataTable ReadSqlForDataTable(ServiceParamter serviceParamter)
        {
            DataTable dt = new DataTable();
            string data = string.Empty;
            string sqlId = serviceParamter.ServiceId;
            string ticString = JsonConvert.SerializeObject(serviceParamter);
            byte[] inArray = System.Text.Encoding.UTF8.GetBytes(ticString);
            string str = Convert.ToBase64String(inArray);
            str = str.Replace("+", "%2B").Replace("+", "%2B");

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("serviceParamter", str);
            string realUrl = url + @"/GetServices/ReadSql";

            try
            {
                string result = HttpHelper.CreateHttpGetResponse(realUrl, dict, G_User.user.Ticket, sqlId);
                ApiResultModel mode = Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(ApiResultModel)) as ApiResultModel;

                if (mode.IsSuccess)
                {
                    data = mode.Data.ToString();
                }
                else
                {
                    throw new Exception(mode.ErrorMessage);
                    // throw new Exception("服务器执行操作失败，错误详情请查看日志");
                }
                // JsonHelper helper = new JsonHelper();
                // dt = JsonHelper.ToDataTable(data);
                dt = Newtonsoft.Json.JsonConvert.DeserializeObject(data, typeof(DataTable)) as DataTable;
            }
            catch (Exception e)
            {
                throw ExceptionHandle(e);
            }
            return dt;
        }

        public bool WirteSql(ServiceParamter serviceParamter)
        {
            bool result = false;
            string sqlId = serviceParamter.ServiceId;
            string ticString = JsonConvert.SerializeObject(serviceParamter);
            byte[] inArray = System.Text.Encoding.UTF8.GetBytes(ticString);
            string str = Convert.ToBase64String(inArray);
            str = str.Replace("+", "%2B").Replace("+", "%2B"); ;

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("", str);

            string realUrl = url + @"/PostServices/WirteSql";

            try
            {
                string strResult = HttpHelper.CreateHttpPostResponse(realUrl, dict, G_User.user.Ticket, sqlId);
                ApiResultModel mode = Newtonsoft.Json.JsonConvert.DeserializeObject(strResult, typeof(ApiResultModel)) as ApiResultModel;

                if (mode.IsSuccess)
                {
                    result = true;
                }
                else
                {
                    throw new Exception(mode.ErrorMessage);
                }

            }
            catch (Exception e)
            {
                throw ExceptionHandle(e);
            }
            return result;
        }

        public string ReadMenuForText(ServiceParamter serviceParamter)
        {
            string data = string.Empty;
            string sqlId = serviceParamter.ServiceId;
            string ticString = JsonConvert.SerializeObject(serviceParamter);
            byte[] inArray = System.Text.Encoding.UTF8.GetBytes(ticString);
            string str = Convert.ToBase64String(inArray);

            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("serviceParamter", str);

            string realUrl = url + @"/GetServices/ReadMenu";

            try
            {
                string result = HttpHelper.CreateHttpGetResponse(realUrl, dict, G_User.user.Ticket, sqlId);

                //   JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                //  string data = jo["Data"].ToString().Replace("\r", "");
                //     data=data.Replace("\n", "");
                //     data = data.Replace(" ", "");
                ApiResultModel mode = Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(ApiResultModel)) as ApiResultModel;

                if (mode.IsSuccess)
                {
                    data = mode.Data.ToString();
                }
                else
                {
                    throw new Exception("服务器执行操作失败，错误详情请查看日志");
                }
            }
            catch (Exception e)
            {
                throw ExceptionHandle(e);
            }

            // JsonHelper helper = new JsonHelper();

            return data;
        }

        #region 执行sql
        public DataTable ExecReadSql(string sql)
        {
            DataTable dt = new DataTable();
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict.Add("sql", sql);

            string realUrl = url + @"/SqlText/ReadSql";
            try
            {
                string result = HttpHelper.CreateHttpGetResponse(realUrl, dict, G_User.user.Ticket, "ExecReadSql");
                ApiResultModel mode = Newtonsoft.Json.JsonConvert.DeserializeObject(result, typeof(ApiResultModel)) as ApiResultModel;
                string data = string.Empty;
                if (mode.IsSuccess)
                {
                    data = mode.Data.ToString();
                }
                else
                {
                    throw new Exception("服务器执行操作失败，错误详情请查看日志");
                }

                dt = Newtonsoft.Json.JsonConvert.DeserializeObject(data, typeof(DataTable)) as DataTable;
            }
            catch (Exception e)
            {
                throw ExceptionHandle(e);
            }
            return dt;
        }
        #endregion
        #endregion

        private Exception ExceptionHandle(Exception e)
        {
            if (e.Message.Contains("(403)"))
            {
                return  new Exception ("该操作用户没有权限！");

            }
            return e;
        }

        internal DataTable ReadDictForDate(ServiceParamter serviceParamter)
        {
            throw new NotImplementedException();
        }
    }
}
